const router = require('express').Router();
const { dbQuery, dbError } = require('../../tools');


router.get('/last', function(req, res) {
    const {user_id} = req.query;
    // 获取此用户最后一条系统消息,仅显示message_content,send_time
    dbQuery(`
        select s.message_content, s.message_type,s.about_group_id,s.about_user_id,s.send_time,c.no_check
        from system_message_table s,
        (
            select count(checked) as no_check 
            from system_message_table s, user_table u 
            where send_time > u.system_message_check_time and s.user_id='${user_id}' and u.id='${user_id}'
        ) c
        where user_id='${user_id}'
        order by send_time desc
        limit 1
    `)
    .then(async data => {
        if (data.length < 1) {
            res.send({code: 1, message:'', send_time: '', no_check: 0})
            return;
        }
        let sendObj = {code: 0, message: '请求错误'};
        const {message_content, message_type, about_user_id, about_group_id, send_time, no_check} = data[0];
        if (message_type === '0' || message_type === '2') {
            sendObj = {
                code: 1, 
                message: message_content, 
                send_time, 
                no_check
            };
        } else if (message_type === '1') {
            const aboutAame = await dbQuery(`
                select u.name as about_user_name, g.group_name as about_group_name
                from user_table u,
                group_table g
                where u.id='${about_user_id}' and g.group_id='${about_group_id}'
            `)
            sendObj = {
                code: 1, 
                message: `${aboutAame[0].about_user_name}${message_content}${aboutAame[0].about_group_name}`,
                send_time, 
                no_check
            };
        }
        res.send(sendObj);
    })
    .catch(err => {
        dbError(res, err);
    });
});

module.exports = router;
